from django.shortcuts import render
from django.http import HttpResponse
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidAppIdException
from wechatpy import parse_message
from wechatpy.client import WeChatClient
from wechatpy.session.redisstorage import RedisStorage
from wechatpy.replies import create_reply
from redis import Redis



# Create your views here.
redis_client = Redis.from_url('redis://127.0.0.1:6379/0')
section_interface = RedisStorage(
    redis_client,
    prefix='wechatpy'
)
app_id = 'wxe1d86653d2a2d740'
secret = '3074b3d0ed468c3f3f5ddf85aae675f8'
wechat_client = WeChatClient(
    app_id,
    secret,
    session=section_interface
)
def test(request):
    return HttpResponse('hello victory')


def index(request):
    token = wechat_client.access_token
    print(r'token: %s' %token)
    if request.method == 'GET':
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        echostr = request.GET.get('echostr')
        token = "szy4760699"
        try:
            check_signature(token, signature, timestamp, nonce)
            return HttpResponse(echostr)
        except InvalidAppIdException:
            pass
    else:
        msg = parse_message(request.body)
        print(msg)
        if msg.type == 'text':
            if msg.content == 'sd':
                reply = create_reply('刘倩是个好同志', message=msg)
            else:
                reply = create_reply('Shidan', message=msg)
        else:
            reply = create_reply('暂时只支持文字', message=msg)
        response = HttpResponse(reply.render(), content_type='application/xml')
        return response
